package com.gu.weixinpaydemo.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.gu.weixinpaydemo.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.Map;

/**
 * 调用微信支付接口；生成二维码
 */
@CrossOrigin
@RestController
@RequestMapping("/pay")
public class PayController {


    @Autowired private IdWorker idWorker;
    @Autowired private HttpClient httpClient;

    @Value("${appid}")
    private String appid;

    @Value("${partner}")
    private String partner;

    @Value("${partnerkey}")
    private String partnerkey;

    @Value("${notifyurl}")
    private String notifyurl;

    @Value("${weipayurl}")
    private String weipayurl;


    /**
     * 调用微信支付接口，放回生成的路径
     * @param amount  金额
     * @return
     */
    @RequestMapping("/weixinPay")
    public Map payController(String amount) {

        //对金额进行一下处理
        if(amount.indexOf(".") > 0) {
            amount = amount.replace(".","");
        }

        //生成订单号
        String orderId = idWorker.nextId()+"";

        //1.创建参数
        Map<String,String> param=new HashMap();//创建参数
        param.put("appid", appid);//公众号
        param.put("mch_id", partner);//商户号
        param.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
        param.put("body", "爱思乐");//商品描述
        param.put("out_trade_no", orderId);//订单号
        param.put("total_fee",amount);//总金额（分）
        param.put("spbill_create_ip", "127.0.0.1");//IP
        param.put("notify_url", notifyurl);//回调地址(随便写)
        param.put("trade_type", "NATIVE");//交易类型
        try {
            //2.生成要发送的xml
            String xmlParam = WXPayUtil.generateSignedXml(param, partnerkey);
            System.out.println(xmlParam);

            //使用HttpClientPost调用微信支付接口
            String result = httpClient.httpClientPost(xmlParam, weipayurl);

            //3.获得结果
            System.out.println(result);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            Map<String, String> map=new HashMap<>();
            map.put("code_url", resultMap.get("code_url"));//支付地址
            map.put("total_fee", amount);//总金额
            map.put("out_trade_no",orderId);//订单号

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }






}
